import pandas as pd
import numpy as np
# df = pd.read_csv("chart.csv", encoding='gbk')
# df_new = df.dropna()
# df_new.to_csv('new_file.csv', encoding='utf-8', index=False)
# df = pd.read_csv("new_file.csv", encoding='utf-8')
# print(df)

# 标准化操作
# from sklearn.preprocessing import StandardScaler
# # 读取数据集
# df = pd.read_csv("new_file.csv")
# # 创建标准化对象
# scaler = StandardScaler()
#
# # 对数据进行标准化
# normalized_data = scaler.fit_transform(df)
#
# # 将标准化后的数据放入一个新的DataFrame中
# df_normalized = pd.DataFrame(normalized_data, columns=df.columns)
#
# # 打印标准化后的数据
# print("标准化后的数据:")
# print(df_normalized)
#
#
# df_normalized.to_csv('df_normalized.csv', encoding='utf-8', index=False)
import pandas as pd
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN, SpectralClustering, Birch
from sklearn.metrics import silhouette_score
from sklearn.model_selection import GridSearchCV

df = pd.read_csv("new_file_with_scores.csv")

features = ['Q2','Q3','Q4','Q5','Q6','Q11','Q10', 'Q12', 'Q13', 'Q14']

kmeans = KMeans()
agglomerative = AgglomerativeClustering()
spectral = SpectralClustering()
birch = Birch()

def silhouette_scorer(estimator, X):
    labels = estimator.fit_predict(X)
    score = silhouette_score(X, labels)
    return score

param_grid = {'n_clusters': range(4,5)}

grid_search = GridSearchCV(kmeans, param_grid=param_grid, scoring=silhouette_scorer)
grid_search.fit(df[features])
best_kmeans = grid_search.best_estimator_
best_kmeans_score = grid_search.best_score_

grid_search = GridSearchCV(agglomerative, param_grid=param_grid, scoring=silhouette_scorer)
grid_search.fit(df[features])
best_agglomerative = grid_search.best_estimator_
best_agglomerative_score = grid_search.best_score_

grid_search = GridSearchCV(spectral, param_grid=param_grid, scoring=silhouette_scorer)
grid_search.fit(df[features])
best_spectral = grid_search.best_estimator_
best_spectral_score = grid_search.best_score_

grid_search = GridSearchCV(birch, param_grid=param_grid, scoring=silhouette_scorer)
grid_search.fit(df[features])
best_birch = grid_search.best_estimator_
best_birch_score = grid_search.best_score_

print("KMeans 轮廓系数:", best_kmeans_score)
print(best_kmeans)
print("\nAgglomerative Clustering 轮廓系数:", best_agglomerative_score)
print(best_agglomerative)
print("\nSpectral Clustering 轮廓系数:", best_spectral_score)
print(best_spectral)
print("\nBirch 轮廓系数:", best_birch_score)
print(best_birch)
import matplotlib.pyplot as plt

best_scores = [best_kmeans_score, best_agglomerative_score, best_spectral_score, best_birch_score]
algorithm_names = ["KMeans", "Agglomerative ", "Spectral ", "Birch"]

# 设置每个算法对应的颜色
colors = ['red', 'grey', 'grey', 'grey']

# 绘制条形图，并根据算法设置颜色
for i, score in enumerate(best_scores):
    plt.bar(algorithm_names[i], score, color=colors[i])
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('聚类算法')
plt.ylabel('最高轮廓系数')

# 添加标题
plt.title('不同聚类算法的最高轮廓系数')

# 显示最佳n_clusters参数
for i, score in enumerate(best_scores):
    plt.text(i, score, f'n_clusters={param_grid["n_clusters"][0]}', ha='center', va='bottom')

# 显示图像
plt.show()